// let {

// } = require("@/common/g3d.min.js") 
import {
  Engine,
  Scene,
  RotatePerspectiveCamera,
  Skybox,
  Geometry
} from 'g3d';
let lx = null,
  ly = null;
class ImageAr {

  /**
   * @param {Object} selector
   * @param {Object} canvas
   * @param {Object} images
   * @param {Object} opt
   */
  constructor(canvas, images, opt) {
    this.canvas = canvas;
    // this.gl = canvas.getContext('webgl');
    this.images = images;
    this.opt = opt || {
      //贴图全部加载完成的回调事件
      textureComplete: (image360) => {}
    }
    this.init();
  }

  /** 
   * 初始化 
   */
  init() {
    let self = this;
    // 创建一个引擎
    this.engine = new Engine(self.canvas);
    // 创建场景
    this.scene = new Scene(this.engine);
    // 创建相机 环绕透视相机
    this.camera = new RotatePerspectiveCamera(this.scene);
    //横向角度
    this.camera.alpha = 0;
    //纵向角度
    this.camera.beta = 0;
    this.camera.radius = 10;
    this.camera.near = 0.001;
    this.camera.far = 2000;
    let cnt = 0;
    // fbudlr 
    let imageListPOsi = ["back", "front", "top", "bottom", "left", "right"]; // 图片顺序 后, 前, 上, 下, 左, 右

    let pos = {}
    for (let i = 0; i < this.images.length; i++) {
      // 小程序这里没有 new Image
      let image = this.canvas.createImage(); //
      pos[imageListPOsi[i]] = image;
      image.onload = () => {
        cnt++;
        if (cnt >= 6) { //pano形式最多6张,也就是正方体的6个面 
          let skybox = new Skybox(self.scene, pos, 100, true);
          console.log(skybox)

          function render() {
            self.scene.render();
            self.requestAnimationFrame(render);
          }

          render();

          //贴图全部加载完成后的回调,外部调用
          self.opt.textureComplete && self.opt.textureComplete(self);
        }
      }
      image.src = this.images[i];
    }
  }


  touchmove(e) {
    let self = this;
    //console.log(e)
    let x = e.touches[0].clientX;
    let y = e.touches[0].clientY;

    self.camera.alpha += (x - lx) / 5;
    this.camera.beta = self.clamp(-90, 90, this.camera.beta - (y - ly) / 5);
    lx = x;
    ly = y;
  }

  touchstart(e) {
    let self = this;
    //console.log(e)
    let x = e.touches[0].clientX;
    let y = e.touches[0].clientY;
    lx = x;
    ly = y;
  }

  touchend(e) {

  }

  /**
   * 重绘界面
   * https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Canvas.requestAnimationFrame.html
   */
  requestAnimationFrame(cb) {
    this.canvas.requestAnimationFrame(cb);
  }

  clamp(min, max, v) {
    return v < min ? min : v > max ? max : v;
  }
}


export default ImageAr